<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hash路由</title>
</head>

<body>

  <ul>
    <li>
      <!-- 通过标签导航  声明式导航 -->
      <a href="#/home">首页</a>
      <!-- location.href='#/home' js方式进行导航切换 编程式导航 -->
    </li>
    <li>
      <a href="#/about">关于</a>
    </li>
  </ul>

  <div id="routerView"></div>

  <script>
    const routerRender = () => {
      // let hash = location.hash || '#/home'
      // let html = component[hash.slice(2)]()
      // document.getElementById('routerView').innerHTML = html
      let html = ''
      try {
        let hash = location.hash || '#/home'
        html = component[hash.slice(2)]()
      } catch (error) {
        html = `<div>404</div>`
      }
      document.getElementById('routerView').innerHTML = html
    }

    const component = {
      home() {
        return `<div>home页面</div>`
      },
      about() {
        return '<div>关于页面</div>'
      }
    }


    window.onload = function () {
      // console.log(location.hash);
      routerRender()
    }

    // 事件，监听地址栏中的hash值变化
    window.addEventListener('hashchange', routerRender)


    // function routerRender() {
    //   let html = component[location.hash.slice(2)]()
    //   document.getElementById('routerView').innerHTML = html
    // }



  </script>

</body>

</html>